// pages/shop/products.js
//获取应用实例
var app = getApp();
var currentShopId = 0;
var currentProduct;
var currentPage = 1;

Page({
  data: {
    categories_actice: 0,
    categories: [],
    products: [],
    empty: false,
    loadMore: true,
    addshow:true,
  },
  onLoad: function () {
    this.setData({
      windowWidth: app.systemInfo.windowWidth
    })
  },
  onReady: function(){
    var that = this;
    app.util.appInfo(app, function(res){
      wx.setNavigationBarTitle({
        title: res.result.name
      });

      that.setData({
        app_name: res.result.name
      });
    });

    if (that.data.products.length == 0) {
      currentPage = 1;
    }
    var shop = wx.getStorageSync('shop');
    currentShopId = shop.id;
    app.func.req('product_cates/index', {
      shop_id: shop.id,
      is_business: true
    }, 'GET', function(res){
      if (res.code == 'error'){
        that.setData({
          empty: true
        })
      }else{
        that.setData({
          empty: false
        })
        var categories_actice = that.data.categories_actice;
      var categories =  app.util.covertProductCates(res.result);
      // 当前分类是否开启
      var curCate = categories[0];
      var cateExist = false;
      for(var i = 0;i<categories.length;i++){
        if (categories_actice == categories[i].id){
          curCate = categories[i];
          cateExist = true;
        }
      }
      if(!cateExist){
        curCate = categories[0];
        categories_actice = categories[0].id;
      }
      that.setData({
        categories: categories,
        curCate: curCate,
        categories_actice: categories_actice,
        products: []
      });
      // 获取该分类下的商品列表
       currentPage = 1;
       //if(that.data.addshow){
      //    that.getProducts(categories_actice);
       //}
      }
    });
  },
  onShow: function (options){
  //  if (this.data.categories.length >= 0) {
      this.refreshProducts();
  //  }
  },
  onHide: function(){
    app.refreshProducts = false;
  },
  refreshProducts: function(){
    // console.log('onPullDownRefresh...')

    var that = this;
    if (that.data.products.length == 0) {
      currentPage = 1;
    }
    var shop = wx.getStorageSync('shop');
    currentShopId = shop.id;
    app.func.req('product_cates/index', {
      shop_id: shop.id,
      is_business: true
    }, 'GET', function(res){
      if (res.code == 'error'){
        that.setData({
          empty: true
        })
      }else{
        that.setData({
          empty: false
        })
        var categories_actice = that.data.categories_actice;
      var categories =  app.util.covertProductCates(res.result);
      // 当前分类是否开启
      var curCate = categories[0];
      var cateExist = false;
      for(var i=0;i<categories.length;i++){
        if (categories_actice == categories[i].id){
          curCate = categories[i];
          cateExist = true;
        }
      }
      if(!cateExist){
        curCate = categories[0];
        categories_actice = categories[0].id;
      }
      that.setData({
        categories: categories,
        curCate: curCate,
        categories_actice: categories_actice,
        products: []
      });
      // 获取该分类下的商品列表
      currentPage = 1;
      that.getProducts(categories_actice);
      }
    });
  },
  //获取当前当前店铺指定分类下的商品列表
  getProducts: function(cateId){
    var that = this;
    that.setData({
      loadMore: false,
      addshow:false,
    })
    wx.showLoading({ title: '数据加载中...', mask: true });
    app.func.req('products/index', {
      shop_id: currentShopId,
      product_cate_id: cateId,
      is_business: true,
      page_index: currentPage,
      page_size: 10
    }, 'GET', function(res){
      if (res.code =="success"){
        var products = app.util.convertProducts(res.result);
        var currentProducts = that.data.products.concat(products);
        that.setData({
          products: currentProducts,
          loadMore: true
        });
        currentPage++;
      }
      wx.hideLoading();
    },{
      'token': wx.getStorageSync('token')
    });
  },
  loadMore: function(){
    var that = this;
    if(that.data.loadMore){
      that.getProducts(that.data.categories_actice);
    }
  },
  //分类切换
  categorySelect: function(e){
    var that = this;
    var id = e.target.dataset.id;
    var categories = that.data.categories;
    var curCate = categories[0];
    for (var i = 0; i < categories.length; i++) {
      if (id == categories[i].id) {
        curCate = categories[i];
      }
    }
    this.setData({
      curCate: curCate,
      categories_actice: id,
      products: []
    })
    //获取商品列表
    currentPage = 1;
    that.getProducts(id);
  },
  categoryDo: function(e){
    var index = e.target.dataset.index;
    var category = this.data.categories[index];
    var that = this;
    var isOpen;
    if (category.status == 1){
      isOpen = '关闭';
    }else{
      isOpen = '开启';
    }
    wx.showActionSheet({
      itemList: ['编辑',isOpen,'删除'],
      success: function(res){
        if(res.tapIndex == 0){
          wx.navigateTo({
            url: './category_new?id=' + category.id
          });
        }else if(res.tapIndex == 1){
          if(category.status == 1){
            that.categoryStatus(category.id, 0)
          }else{
            that.categoryStatus(category.id, 1)
          }

        }else if(res.tapIndex == 2){
          that.categoryStatus(category.id,2)
        }
      }
    });
  },
  categoryStatus: function(id,status){
    var that = this;
    app.func.req('product_cates/status',{
      id: id,
      status: status,
      shop_id: currentShopId
    },'POST',function(res){
      if (res.code == 'success') {
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000
        })
        wx.showLoading({ title: '数据加载中...', mask: true });
        app.func.req('product_cates/index', {
          shop_id: currentShopId,
          is_business: true
        }, 'GET', function (res) {
          var categories = app.util.covertProductCates(res.result);
          var curCate;
          for(var i = 0;i < categories.length;i++){
            if(categories[i].id == id){
              curCate = categories[i];
              categories[i].active=true;
            }
          }
          that.setData({
            categories: categories,
            curCate: curCate,
            products: []
          });
          // 获取该分类下的商品列表
          currentPage = 1;
          that.getProducts(id);
        });
      }
    },{
      'token': wx.getStorageSync('token')
    })
  },
  add: function(){
    var that = this;
    wx.showActionSheet({
      itemList: ['添加分类','添加商品'],
      success: function(res){
        if(res.tapIndex == 0){
          wx.navigateTo({
            url: './category_new'
          })
        }else if(res.tapIndex == 1){

          if(that.data.categories.length){
            wx.navigateTo({
              url: './product_new'
            })
          }else{
            wx.showToast({
              title: '请添加分类',
              icon: 'info',
              duration: 2000
            })
          }

        }else {
          that.refreshProducts();
        }
      }
    });
  },
  productDo: function(e){
    var id = e.target.dataset.id;
    var index = e.target.dataset.index;
    var that = this;
    wx.showActionSheet({
        itemList: ['编辑', '上架', '下架', '删除', '生成海报', '发起点赞'],
      success: function(res){
        if(res.tapIndex == 0){
          wx.navigateTo({
            url: './product_new?id=' + id
          });
        }else if(res.tapIndex == 1){
          that.updateStatus(id, 1); //上架
        }else if(res.tapIndex == 2){
          that.updateStatus(id, 0); //下架
        }else if(res.tapIndex == 3){
          that.updateStatus(id, 2); //删除
        } else if(res.tapIndex == 4){
          //二维码海报
          wx.showLoading({ title: '海报生成中...', mask: true });
          app.func.req('products/qrcode',{
            id: id
          },'POST',function(res){
            if (res.code == "success"){
              wx.hideLoading();
              wx.previewImage({
                urls: [res.result],
              })
            }
          }, {
            'token': wx.getStorageSync('token')
          })
        }else if(res.tapIndex == 5){
          //发起点赞
          if (that.data.products[index].specs.length==0){
            wx.navigateTo({
              url: './zan?id=' + id
            });
          }else{
            wx.showModal({
              title: '提示',
              content: '多规格的商品暂不支持点赞',
              showCancel: false,
              confirmText: '朕知道了',
            })
          }
        }
      }
    })
  },
  platproductDo: function (e) {
    var id = e.target.dataset.id;
    var index = e.target.dataset.index;
    var that = this;
    wx.showActionSheet({
      itemList: ['上架', '下架', '删除', '生成海报'],  //'添加秒杀'
      success: function (res) {
        if (res.tapIndex == 0) {
          that.updateStatus(id, 1); //上架
        } else if (res.tapIndex == 1) {
          that.updateStatus(id, 0); //下架
        } else if (res.tapIndex == 2) {
          that.updateStatus(id, 2); //删除
        } else if (res.tapIndex == 3) {
          //二维码海报
          wx.showLoading({ title: '海报生成中...', mask: true });
          app.func.req('products/qrcode', {
            id: id
          }, 'POST', function (res) {
            if (res.code == "success") {
              res.result = res.result.replace(/(^\s*)|(\s*$)/g, "");
              wx.hideLoading();
              wx.previewImage({
                urls: [res.result],
              })
            }
          }, {
              'token': wx.getStorageSync('token')
            })
            
        } 
         else if(res.tapIndex ==4){
            wx.navigateTo({
                 url: './product_new?product_id=' + id
             });
         }
      }
    })
  },
  updateStatus: function(id, status){
    var that = this;
    app.func.req('products/status', {id: id, status: status}, 'POST', function(res){
      if(res.code == 'error' && res.msg == 'product_num.nix'){
        wx.showToast({
          title: '库存为空，无法上架',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      if(res.code == 'error' && res.msg == 'goods_status.error'){
        wx.showToast({
          title: '商品库已下架',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      if(res.code == 'success'){
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000
        })
        that.setData({
          products: []
        })
        currentPage = 1;
        that.getProducts(that.data.curCate.id);

      }
    },{
      'token': wx.getStorageSync('token')
    });
  }
})
